package com.lingz.manager.modules.wuxue.serviceimpl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lingz.manager.modules.wuxue.entity.*;
import com.lingz.manager.modules.wuxue.mapper.*;
import com.lingz.manager.modules.wuxue.entity.dto.HistoryDataParam;
import com.lingz.manager.modules.wuxue.service.DataInfoService;
import com.lingz.manager.modules.wuxue.utils.DeviceDataUtil;
import com.lingz.manager.modules.wuxue.utils.SendRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional
public class DataInfoServiceImpl extends ServiceImpl<HuangshiDataMapper, HuangshiData> implements DataInfoService {

    @Value("${shujujiekou.huangshi}")
    String huangshiUrl;
    @Value("${shujujiekou.yikeman}")
    String yikemanUrl;

    @Value("${shujujiekou.shanxun}")
    String shanxunUrl;

    @Value("${shujujiekou.waterConservancy}")
    String waterConservancyUrl;

    @Autowired
    DeviceInfoMapper deviceInfoMapper;

    @Autowired
    HuangshiDataMapper dataInfoMapper;

    @Autowired
    YikemanDataMapper yikemanDataMapper;

    @Autowired
    TuopuInsectDataMapper tuopuInsectDataMapper;

    @Autowired
    WaterConservancyDataMapper waterConservancyDataMapper;

    @Override
    public void requestDataInfoToDB() {

        SendRequest request = new SendRequest();
        String jsonResponse = request.sendGet(huangshiUrl);

        JSONObject responseJson = JSONObject.parseObject(jsonResponse);
        if (responseJson != null && responseJson.containsKey("data")){
            JSONArray data = responseJson.getJSONArray("data");
            List<HuangshiData> huangshiDataList = new ArrayList<>();
            if(data!= null && !data.isEmpty()){
                for(int i = 0 ; i <data.size(); i++){
                    JSONObject jsonObject = data.getJSONObject(i);
                    try {
                        HuangshiData huangshiData = DeviceDataUtil.parseJsonToHSWeatherData(jsonObject);
                        huangshiDataList.add(huangshiData);
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            dataInfoMapper.insertBatchSomeColumn(huangshiDataList);
        }
    }

    public void requestYikemanDataToDB() {
        SendRequest request = new SendRequest();
        String jsonResponse = request.sendGet(yikemanUrl);
        JSONObject responseJson = JSONObject.parseObject(jsonResponse);
        if (responseJson != null && responseJson.containsKey("resultData")){
            JSONArray data = responseJson.getJSONArray("resultData");
            List<YikemanData> dataInfos = new ArrayList<>();
            if(data!= null && !data.isEmpty()){
                for(int i = 0 ; i <data.size(); i++){
                    JSONObject jsonObject = data.getJSONObject(i);
                    try {
                        YikemanData yikemanData = DeviceDataUtil.parseJsonToYKMInsectData(jsonObject);
                        dataInfos.add(yikemanData);
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            yikemanDataMapper.insertBatchSomeColumn(dataInfos);
        }
    }

    public void requestShanxunDataToDB() {
        SendRequest request = new SendRequest();
        String jsonResponse = request.sendGet(shanxunUrl);

        JSONObject responseJson = JSONObject.parseObject(jsonResponse);

        if (responseJson != null && responseJson.containsKey("resultData")){
            JSONArray data = responseJson.getJSONArray("resultData");
            List<YikemanData> dataInfos = new ArrayList<>();
            ObjectMapper objectMapper = new ObjectMapper();
            if(data!= null && !data.isEmpty()){
                for(int i = 0 ; i <data.size(); i++){
                    JSONObject jsonObject = data.getJSONObject(i);
                    try {
                        YikemanData yikemanData = objectMapper.readValue(jsonObject.toString(), YikemanData.class);
                        dataInfos.add(yikemanData);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            yikemanDataMapper.insertBatchSomeColumn(dataInfos);
        }
    }

    @Override
    public Object getWeatherConditionByDeviceId(String deviceId) {
        if(deviceId.equals("YBQ0000145") ) {
            LambdaQueryWrapper<HuangshiData> wrapper = new LambdaQueryWrapper<>();
            wrapper.orderByDesc(HuangshiData::getCollectTime);
            Page<HuangshiData> dataInfoPage = new Page<>(1, 1);
            page(dataInfoPage, wrapper);
            List<HuangshiData> huangshiData = dataInfoPage.getRecords();
            return huangshiData.get(0);
        }
        return null;
    }

    @Override
    public Object getHistoryData(HistoryDataParam historyDataParam) {
        if (historyDataParam.getDeviceId().equals("YBQ0000145")) {
            QueryWrapper<HuangshiData> wrapper = new QueryWrapper<>();
            wrapper.select("collect_time",historyDataParam.getField());
            wrapper.between("collect_time", historyDataParam.getStartTime(), historyDataParam.getEndTime());
            wrapper.orderByAsc("collect_time");
            return dataInfoMapper.selectMaps(wrapper);
        }
        return null;
    }

    @Override
    public String requestTuopuInsectDataToDB(String start_date, String end_date) {
        LambdaQueryWrapper<DeviceInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceInfo::getFactory, "托普");
        List<DeviceInfo> deviceInfos = deviceInfoMapper.selectList(wrapper);
        String res = "";
        for (DeviceInfo deviceInfo : deviceInfos) {
            String deviceId = deviceInfo.getDeviceId();
            if (deviceId != null) {
                String tpUrl = DeviceDataUtil.createTPUrl("1", deviceId, start_date, end_date);
                SendRequest request = new SendRequest();
                String jsonResponse = request.sendPost(tpUrl);
                res = handleTPData(jsonResponse);
            }
        }
        return res;
    }

    @Override
    public void requestWaterConservancyDataToDB() {
        SendRequest request = new SendRequest();
        String jsonResponse = request.sendGet(waterConservancyUrl);

        JSONArray data = JSONArray.parseArray(jsonResponse);
        List<WaterConservancyData> waterConservancyDataList = new ArrayList<>();
        if(data!= null && !data.isEmpty()){
            for(int i = 0 ; i <data.size(); i++){
                JSONObject jsonObject = data.getJSONObject(i);
                String stname = jsonObject.getString("stname");
                JSONObject flowVO = jsonObject.getJSONObject("flowVO");
                if(flowVO != null) {
                    try {
                        WaterConservancyData waterConservancyData = DeviceDataUtil.parseJsonToWaterConservancyData(flowVO, stname);
                        waterConservancyDataList.add(waterConservancyData);
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        waterConservancyDataMapper.insertBatchSomeColumn(waterConservancyDataList);
    }

    private String handleTPData(String jsonResponse) {
        JSONObject responseJson = JSONObject.parseObject(jsonResponse);
        if (responseJson != null ){
            if(responseJson.containsKey("data")) {
                List<TuopuInsectData> tuopuInsectDataList = new ArrayList<>();
                JSONObject data = responseJson.getJSONObject("data");
                JSONArray list = data.getJSONArray("list");
                for (int i = 0; i < list.size(); i++) {
                    JSONObject jsonObject = list.getJSONObject(i);
                    JSONArray imgList = jsonObject.getJSONArray("img_list");
                    String deviceId = jsonObject.getString("serial_num");
                    for (int j = 0; j < imgList.size(); j++) {
                        JSONObject imgListJSONObject = imgList.getJSONObject(j);
                        try {
                            TuopuInsectData tuopuInsectData = DeviceDataUtil.parseJsonToTPInsectData(imgListJSONObject, deviceId);
                            tuopuInsectDataList.add(tuopuInsectData);
                        } catch (ParseException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
                tuopuInsectDataMapper.insertBatchSomeColumn(tuopuInsectDataList);
            }
            return responseJson.getString("msg");
        }
        return "";
    }
}
